package api

import (
	"context"
	"net/http"
	"os"
	"time"

	"gitee.com/liumou_site/go-network-monitoring/service"
	"gitee.com/liumou_site/go-network-monitoring/templates"
	"gitee.com/liumou_site/logger"
	"github.com/gin-gonic/gin"
)

// PageAPIHandler 页面渲染API处理器
type PageAPIHandler struct {
	networkService *service.NetworkService
	systemService  *service.SystemService
}

// NewPageAPIHandler 创建页面API处理器实例
func NewPageAPIHandler(startTime time.Time) *PageAPIHandler {
	return &PageAPIHandler{
		networkService: service.NewNetworkService(),
		systemService:  service.NewSystemService(startTime),
	}
}

// Index 处理根路径请求，返回网络监控页面
func (h *PageAPIHandler) Index(renderer *templates.RenderHtml) gin.HandlerFunc {
	return func(c *gin.Context) {
		// 获取所有网络接口的统计数据
		_, err := h.networkService.GetNetworkStats()
		if err != nil {
			logger.Error("Failed to get network stats", err)
			c.String(http.StatusInternalServerError, "Failed to get network stats: %v", err)
			return
		}

		// 计算所有网络接口的速度
		_, _, err = h.networkService.CalculateSpeed(context.Background(), 1*time.Second)
		if err != nil {
			logger.Error("Failed to calculate network speed", err)
			c.String(http.StatusInternalServerError, "Failed to calculate network speed: %v", err)
			return
		}

		// 获取真实的主机名和IP地址
		hostname, _ := os.Hostname()
		ipv4 := "127.0.0.1"

		// 准备模板数据
		data := templates.HtmlData{
			Hostname:      hostname,
			InterfaceName: "All Interfaces",
			Ipv4:          ipv4,
			Version:       "1.2.0",
			AppName:       "Go网络监控",
			Runtime:       h.systemService.BuildHtmlData(hostname, "All Interfaces", ipv4, "1.2.0", "Go网络监控").Runtime,
		}

		// 渲染HTML
		htmlContent := renderer.GetHtmlText(data)
		c.Data(http.StatusOK, "text/html; charset=utf-8", []byte(htmlContent))
	}
}

// ProcessMonitorIndex 渲染进程监控页面
func (h *PageAPIHandler) ProcessMonitorIndex(renderer *templates.RenderHtml) gin.HandlerFunc {
	return func(c *gin.Context) {
		// 获取主机名
		hostname, _ := os.Hostname()
		ipv4 := "127.0.0.1"

		// 准备模板数据
		data := templates.HtmlData{
			Hostname:      hostname,
			InterfaceName: "进程监控",
			Ipv4:          ipv4,
			Version:       "1.2.0",
			AppName:       "Go网络监控",
			Runtime:       h.systemService.BuildHtmlData(hostname, "进程监控", ipv4, "1.2.0", "Go网络监控").Runtime,
		}

		// 渲染HTML
		htmlContent := renderer.GetProcessHtmlText(data)
		c.Data(http.StatusOK, "text/html; charset=utf-8", []byte(htmlContent))
	}
}

// GetVersionAPI 返回后端版本信息
func (h *PageAPIHandler) GetVersionAPI(version, appName, description string) gin.HandlerFunc {
	return func(c *gin.Context) {
		versionInfo := h.systemService.GetVersionInfo(version, appName, description)
		c.JSON(http.StatusOK, versionInfo)
	}
}